#!/usr/bin/env node
import { setConfig } from 'src';
import { getInput, select } from './utils';
import { ConfigZod } from './types';
import * as fs from 'fs';

/** 
 * 配置文件生效
 */
export async function markConfigEffect(config: {[key: string]: string | true}) {
  if (!config.file) {
    do {
      config.file = await getInput('请输入配置文件(.json)路径：');
    } while (
      !(config.file as string).trim() || 
      !config.file.toString().endsWith('.json')
    );
  }
  if (!fs.existsSync((config.file as string))) return console.log(`>>> 文件不存在: ${config.file}`);
  try {
    const content = fs.readFileSync(config.file as string, 'utf-8');
    setConfig(ConfigZod.parse(JSON.parse(content)));
    console.log('>>> 设置成功!');
  } catch (e) {
    console.log(e);
  }
}

/**
 * 解析参数
 */
function processArgs(argList: Array<string>) {
  return argList.reduce((result, item) => {
    if (item) {
      const [key, value] = item.split('=');
      result[key] = value === undefined ? true : value;
    }
    return result;
  }, {} as {[key: string]: string | true});
}

function main() {
  console.log('######## local-cli脚手架 ########');
  /** 选项配置 */
  const options = [
    { name: '快捷配置', value: 'set:config', handler: markConfigEffect },
    { name: '启动项目', value: 'dev', handler: async (config: {[key: string]: string | true}) => { console.log('TODO'); } },
  ];
  /**
   * 参数选择
   */
  const arg0 = process.argv.slice(2, 3)[0];
  
  if (arg0 && options.find(item => item.value === arg0)) { /** 直接匹配了选项 */
    const option = options.find(item => item.value === arg0);
    console.log(`${option?.name} 👈`);
    option?.handler(processArgs(process.argv.slice(3)));
    return;
  }
  /**
   * 交互选择
   */
  select('请选择要执行的操作', options).then(async value=>{
    options.find(item => item.value === value)?.handler(processArgs(process.argv.slice(2)));
  })
}

main();